package com.codinghero.example.http.router;

import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;

public class RouterSwitcher {

	public boolean open() throws IOException{
		return this.switches(true);
	}

	public boolean close() throws IOException{
		return this.switches(false);
	}
	
	public boolean switches(boolean turner) throws IOException {
		
		RouterAdminConfig config = new RouterAdminConfig();
		HttpHost targetHost = new HttpHost(config.getIp(), config.getPort(),
				config.getProtocol());

		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope(targetHost.getHostName(),targetHost.getPort()),
					new UsernamePasswordCredentials(
							config.getLoginName(), config.getLoginPassword()));

			// Create AuthCache instance
			AuthCache authCache = new BasicAuthCache();
			// Generate BASIC scheme object and add it to the local auth cache
			BasicScheme basicAuth = new BasicScheme();
			authCache.put(targetHost, basicAuth);

			// Add AuthCache to the execution context
			BasicHttpContext localcontext = new BasicHttpContext();
			localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

			HttpGet httpget = null;
			if (turner)
				httpget = new HttpGet(config.getOpenAdslUrl());
			else
				httpget = new HttpGet(config.getCloseAdslUrl());
            
			HttpResponse response = httpclient.execute(targetHost, httpget,
					localcontext);
			// HttpEntity entity = response.getEntity();
			// if (entity != null) {
			// System.out.println("Response content length: "
			// + entity.getContentLength());
			// }
			// EntityUtils.consume(entity);

			return response.getStatusLine().getStatusCode() == 200;

		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

}
